import socket
import urllib.request
import urllib.parse
import string
from bs4 import BeautifulSoup
from urllib.parse import unquote, quote


# 访问网页获取数据
def getHtml(valid):
	print("{0:-^60}".format(""))
	url = "http://dict.youdao.com/w/" + quote(valid) + "/#keyfrom=dict2.top"
	try:
		res = urllib.request.urlopen(url, timeout=5)
		html = res.read().decode('utf-8')
		# print(html)
		return BeautifulSoup(html, 'html.parser')
	except socket.timeout as e:
		print("|| Timed out: {}".format(e))
		return None


# 中-英
def ch_en():
	i = 0
	try:
		while True:
			buff = soup.select('div #phrsListTab')[0].select('div .trans-container')[0].select('ul')[0].select('a')[
				i].string
			if buff is None:
				i += 1
				continue
			buffs.append(buff)
			print("||" + str(i + 1) + ") " + buff)
			i += 1
	except IndexError as e:
		if i != 0:
			print("{0:->60}".format("\n\n"))
			return 'ch_en'
		return 'en_ch'


# 英-中
def en_ch():
	i = 0
	try:
		while True:
			buff = soup.select('div #phrsListTab')[0].select('div .trans-container')[0].select('ul')[0].select('li')[
				i].string
			if buff is None:
				i += 1
				continue
			buffs.append(buff)
			print("||" + str(i + 1) + ") " + buff)
			i += 1
	except IndexError as e:
		if i != 0:
			print("{0:->62}".format("\n\n"))
			return 'en_ch'
		return 'ch_en'


# 导出单词本到指定路径
def output(path):
	wordBook = open(".\\YoudaoDictWords.txt", 'a')
	wordBook.close()
	try:
		outfile = open(path + ".\\YoudaoDictWords_output.txt", "w+")
		wordBook = open(".\\YoudaoDictWords.txt", "r+")
		inword = wordBook.readline()
		while inword != '':
			outfile.write(inword)
			inword = wordBook.readline()
		outfile.close()
		wordBook.close()
		return True
	except FileNotFoundError as e:
		return False

	except OSError as e:
		return False

	else:
		return False


buffs = ['']  # 缓冲区
lastMode = ''  # 上次查询模式：中-英or英-中
print("{0:-^60}".format(""))
print("||Quick_YoudaoDict v2021.7 | Develop by Hoyin.")
print("{0:-^60}".format(""))
print("||输入中英单词以查询\n||输入\"apd:::\"或\"append:::\"以添加词条\n||输入\"output:::\"以导出单词本\n||输入\"exit:::\"以退出")
while 1:
	print("{0:-^60}".format(""))
	content = input("||查询:")
	# ===============选项===============
	if content == "exit:::":
		break
	# 添加词条
	if content == "apd:::" or content == "append:::":
		if len(buffs) == 1:
			print("||未找到查询记录")
			continue

		try:
			if len(buffs) - 1 == 1:
				index = 1
			else:
				index = int(input("||上一次查询记录中包含" + str(len(buffs) - 1) + "个词条，请输入词条序号："))
		except ValueError as e:
			print("||请输入词条序号")
			continue

		if index > len(buffs) - 1:
			print("||未找到序号为" + str(int(index)) + "的词条，请检查后重试")
			continue

		if lastMode == 'ch_en':
			soup = getHtml(buffs[index])
			if soup is None:
				continue
			tmp = soup.select('div .trans-container')[0].select('ul')[0].select('li')[
				index - 1].string  # ch
			buffs[0] = buffs[index]
			buffs[index] = tmp

		# 写入词条到本地文件
		wordBook = open(".\\YoudaoDictWords.txt", 'a')
		wordBook.close()
		wordBook = open(".\\YoudaoDictWords.txt", 'r+')
		if wordBook.readline():
			wordBook.write("\n")
		wordBook.close()
		wordBook = open(".\\YoudaoDictWords.txt", 'a')
		wordBook.write(buffs[0])
		wordBook.write(" _ ")
		wordBook.write(buffs[index])
		wordBook.close()
		print("|| \"" + buffs[0] + " _ " + buffs[index] + "\" 词条已添加")
		continue

		# 如果最近查询模式为中-英，在写入到文件之前应当把写入顺序调换
		if lastMode == 'ch_en':
			tmp = buffs[index]
			buffs[index] = buffs[0]
			buffs[0] = tmp

	if content == "output:::":
		while True:
			print("输入\"back:::\"返回上一级")
			output_path = input("请输入导出位置： ")
			if output_path == "back:::":
				break
			if output(output_path):
				print("导出成功，请到\"" + output_path + "\\YoudaoDictWords_output.txt\" 查看")
				break
			else:
				print("导出失败，导出目录不存在，请检查后重试！")
				break
		continue

	soup = getHtml(content)
	if soup is None:
		continue
	buffs = [content]
	lastMode = en_ch()
	lastMode = ch_en()
	if len(buffs) == 1:
		print("||未找查询到结果")
